package com.superatom.springboot.controller;

import com.superatom.springboot.domain.Result;
import com.superatom.springboot.domain.TUsers;
import com.superatom.springboot.repository.UsersRepository;
import com.superatom.springboot.service.UsersService;
import com.superatom.springboot.utils.ResultUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;
import java.util.List;

@RestController
public class UsersController {

    @Autowired
    private UsersRepository usersRepository;
    @Autowired
    private UsersService usersService;

    /**
     * 查询全部人员
     * @return
     */
    @GetMapping("/users")
    public List<TUsers> usersList(){
        return usersRepository.findAll();
    }

    /**
     * 新增人员
     * @param users
     * @return
     */
    @PostMapping("/users")
    public Result<TUsers> usersAdd(@Valid TUsers users, BindingResult bindingResult){
        if (bindingResult.hasErrors()){
            return ResultUtils.error(1, bindingResult.getFieldError().getDefaultMessage());
        }
        return ResultUtils.success(usersRepository.save(users));
    }

    /**
     * 根据id查找人员
     * @param id
     * @return
     */
    @GetMapping("/users/{id}")
    public TUsers usersFindOne(@PathVariable("id") Integer id){

        return usersRepository.findById(id).get();
    }

    /**
     * 更新人员
     * @param id
     * @param users
     * @return
     */
    @PutMapping("/users/{id}")
    public TUsers usersUpdate(@PathVariable("id") Integer id, TUsers users){
        users.setId(id);
        return usersRepository.save(users);
    }

    /**
     * 删除人员
     * @param id
     */
    @DeleteMapping("/users/{id}")
    public void usersDelete(@PathVariable("id") Integer id){
        usersRepository.deleteById(id);
    }

    /**
     * 根据年龄查找人员
     * @param age
     * @return
     */
    @GetMapping("/users/phone/{age}")
    public List<TUsers> findListUserByAge(@PathVariable("age") Integer age){
        return usersRepository.findByAge(age);
    }

    /**
     * 同时新增两个人员
     */
    @PostMapping("/users/two")
    public void saveTwo(){
        usersService.saveUserTwo();
    }

    @GetMapping("/users/getAge/{id}")
    public void usersGetAge(@PathVariable("id") Integer id) throws Exception {
        usersService.getAge(id);
    }
}
